const fs = require('fs')
const path = require('path')
// 输入参数
const arguments = process.argv.splice(2)
const file = 'C:/Users/liuzy/Documents/ad_domains.js'//arguments[0]
// 输入文件
if (!fs.existsSync(file)) {
    console.log('file not exists')
    return
}
// 文本
const data = fs.readFileSync(file, 'utf-8')
if (!data) {
    console.log('file is empty')
    return
}
// 行
const lines = data.split('\n')
// 规则
const rules = []
// 去重
const repeat = {}
for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim()
    if (line.startsWith('#')) {
        continue
    }
    const arr = line.split(' ')
    const rule = { ip: '127.0.0.1', domain: '', s: ''}
    for (let j = 0; j < arr.length; j++) {
        if (arr[j]) {
            if (rule.ip === '127.0.0.1' && /^[0-9\.]+$/.test(arr[j])) {
                rule.ip = arr[j]
                continue
            }
            if (rule.domain === '') {
                rule.domain = arr[j]
                break
            }
        }
    }
    if (rule.domain === '') {
        continue
    } else {
        rule.s = rule.domain.split('.').reverse().join('.')
    }
    if (repeat[rule.domain] !== true) {
        repeat[rule.domain] = true
        rules.push(rule)
    }
}
// 排序
rules.sort(function(a, b) {
    return (a.s > b.s ? 1 : -1)
})
// 输出
const dir = path.dirname(file)
const name = path.basename(file)
const ext = path.extname(file)
const new_file = path.join(dir, name + '_sort' + ext)
const new_data = []
for (let i = 0; i < rules.length; i++) {
    new_data.push(rules[i].ip + ' ' + rules[i].domain)
}
fs.writeFileSync(new_file, new_data.join('\n'))